# -*- coding: utf-8 -*-
from django.http import Http404
from django.db import models
from django.shortcuts import get_object_or_404, render_to_response
from django import newforms as forms
from django.core.urlresolvers import reverse
from Resource import resource_registry


def check_resource(app, model, key):
    Class = models.get_model(app, model)
    if Class is None:
        raise Http404("can not find model: %s/%s" % (app, model))
    try:
        return resource_registry[Class][key], Class
    except KeyError:
        raise Http404("the model does not support rest views")



def get_list_or_create(request, key, app, model):
    resource, Class = check_resource(app, model, key)
    if request.method == "GET":
        # 获取列表
        return resource.get_list(request, Class)
    elif request.method == "POST":
        # 创建一条记录
        return resource.create(request, Class)


def new(request, key, app, model):
    resource, Class = check_resource(app, model, key)
    Form = forms.form_for_model(Class)
    form = Form()
    kwargs = {"key": key, "app": app, "model": model}
    data = {"form": form, "hash": hash(form),
            "url": reverse(get_list_or_create, kwargs=kwargs),
            "title": "创建一条记录", "submit": "创建"}
    return render_to_response("resource/common_form.html", data)


def rud(request, key, app, model, id):
    # read, update, delete 操作
    resource, Class = check_resource(app, model, key)
    obj = get_object_or_404(Class, id=id)
    if request.method == "GET":
        obj_list = Class.objects.filter(id=id)
        if not obj_list:
            raise Http404("can not find model: %s/%s" % (app, model))
        return resource.read(request, obj_list, id=id)
    elif request.method == "POST":
        # prototype 风格
        method = request.POST.get("_method", "POST").upper()
        if method == "PUT":
            return resource.update(request, obj)
        elif method == "DELETE":
            return resource.delete(request, obj)
        else:
            raise Http404("_method: %s can not be supported" % method)
    elif request.method == "PUT":
        return resource.update(request, obj)
    elif request.method == "DELETE":
        return resource.delete(request, obj)


def edit(request, key, app, model, id):
    resource, Class = check_resource(app, model, key)
    obj = get_object_or_404(Class, id=id)
    Form = forms.form_for_instance(obj)
    form = Form()
    kwargs = {"key": key, "app": app, "model": model, "id": id}
    data = {"form": form, "hash": hash(form),
            "url": reverse(rud, kwargs=kwargs),
            "title": "修改记录", "submit": "修改",
            "method": "put", "delete_url": reverse(rud, kwargs=kwargs)}
    return render_to_response("resource/common_form.html", data)
